package com.futvan.z.erp.zproduct;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;

import com.futvan.z.framework.core.SuperService;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zform.z_form_table_column;
import com.futvan.z.system.zregex.z_regex;
import org.apache.commons.beanutils.BeanUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;

@Controller
public class Z_productZ_product_save_and_add_buttonButtonAction extends SuperAction {

    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/z_product_save_and_add_button")
    public @ResponseBody
    Result z_product_save_and_add_button(@RequestParam HashMap<String, String> bean) throws Exception {
        Result result = new Result();
        String PageType = bean.get("PageType");
        if (z.isNotNull(PageType)) {
            if ("add".equals(PageType)) {

                //获取表名
                String table_name = String.valueOf(bean.get("tableId"));

                //根据表名获取表信息
                z_form_table table = z.tables.get(table_name);
                if (table == null) {
                    throw new Exception("tableId无效");
                }
                List<z_form_table_column> columnList = table.getZ_form_table_column_list();
                //根据List转成Map
                HashMap<String, z_form_table_column> columnMap = new HashMap<String, z_form_table_column>();
                for (int i = 0; i < columnList.size(); i++) {
                    z_form_table_column column = columnList.get(i);
                    columnMap.put(column.getColumn_id(), column);
                }
                //插入前事件
                insertBefore(bean, table, columnMap, columnList);

                //生成ZID
                if (z.isNotNull(bean.get("zid"))) {

                    String sql = "select * from z_product where zid = '" + bean.get("number") + "'";
                    Object select = sqlSession.selectOne("select", sql);
                    if (select == null) {
                        bean.put("zid", bean.get("number"));
                    } else {
                        result.setCode(Code.ERROR);
                        result.setMsg("inser异常，产品编号重复");
                        return result;
                    }
                }

                //创建执行SQL
                String sql = CreateInsertSQL(bean, table, columnMap, columnList);
                int count = 0;
                if (z.isNotNull(table.getDbid())) {

                    count = sqlSession.insert("insert", sql);

                } else {
                    z.Exception("insert: dbid is null");
                }

                if (count != 1) {
                    result.setCode(Code.ERROR);
                    result.setMsg("insert异常，同时插入" + count + "条数据");
                } else {
                    //执行插入后事件
                    insertAfter(bean, table, columnMap, columnList);

                    //设置返回
                    result.setCode(Code.SUCCESS);
                    result.setMsg("保存成功");
                    result.setData(BeanUtils.getProperty(bean, "zid"));
                }
//                return result;
//                result = commonService.insert(bean, request);
            } else if ("edit".equals(PageType)) {
                result = commonService.update(bean, request);
            } else {
                result.setCode(Code.ERROR);
                result.setMsg("页面保存类型错误|PageType:" + PageType);
            }
        } else {
            result.setCode(Code.ERROR);
            result.setMsg("页面保存类型为空|PageType is null");
        }
        return result;
    }


    /**
     * 创建插入SQL
     *
     * @param bean
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws Exception
     */
    private String CreateInsertSQL(HashMap<String, String> bean, z_form_table table, HashMap<String, z_form_table_column> columnMap, List<z_form_table_column> columnList) throws Exception {

        if (table != null && columnList != null && columnList.size() > 0) {
            //创建SQL
            StringBuffer sql = new StringBuffer();
            sql.append("insert into " + table.getTable_id() + " ( ");
            for (z_form_table_column column : columnList) {
                String name = column.getColumn_id();//获取参数名
                String value = bean.get(column.getColumn_id());
                if (!"zid".equals(name)
                        && !"create_user".equals(name)
                        && !"update_user".equals(name)
                        && !"create_time".equals(name)
                        && !"update_time".equals(name)
                        && !"seq".equals(name)
                        && !"orgid".equals(name)
                        && !"zversion".equals(name)
                        && column != null) {
                    if (z.isNotNull(value)) {
                        //字段必须是表定义中包含的字段
                        if (z.isNotNull(columnMap.get(name))) {
                            sql.append(name + " , ");
                        }
                    } else if (z.isNotNull(column.getColumn_default_type())) {
                        //添加默认值字段
                        sql.append(name + " , ");
                    }
                }
            }
            sql.append(" create_user,create_time,update_user,update_time,orgid,zversion,zid ) values ( ");
            //添加值
            for (z_form_table_column column : columnList) {
                String name = column.getColumn_id();//获取参数名
                String value = bean.get(column.getColumn_id());
                if (!"zid".equals(name)
                        && !"create_user".equals(name)
                        && !"update_user".equals(name)
                        && !"create_time".equals(name)
                        && !"update_time".equals(name)
                        && !"seq".equals(name)
                        && !"orgid".equals(name)
                        && !"zversion".equals(name)
                        && column != null) {

                    String Column_type = column.getColumn_type();//获取字段类型

                    if (z.isNotNull(value)) {
                        if ("2".equals(Column_type)) {//如果是数值，不用加单引号
                            sql.append(value + ",");
                        } else {
                            //内容特殊字符转意
                            value = StringUtil.conversionSQL(value);
                            sql.append("'" + value + "',");
                        }
                    } else if (z.isNotNull(column.getColumn_default_type())) {
                        //添加默认值
                        if ("0".equals(column.getColumn_default_type())) {//固定值
                            sql.append("'" + column.getColumn_default() + "',");
                        } else if ("1".equals(column.getColumn_default_type())) {//系统时间
                            sql.append("'" + DateUtil.getDateTime() + "',");
                        } else if ("2".equals(column.getColumn_default_type())) {//系统日期
                            sql.append("'" + DateUtil.getDate() + "',");
                        } else if ("3".equals(column.getColumn_default_type())) {//当前用户
                            sql.append("'" + bean.get("session_userid") + "',");
                        } else if ("4".equals(column.getColumn_default_type())) {//当前组织
                            sql.append("'" + bean.get("session_orgid") + "',");
                        } else if ("5".equals(column.getColumn_default_type())) {//编号
                            sql.append("'" + z.newNumber() + "',");
                        } else if ("6".equals(column.getColumn_default_type())) {//主键编号
                            sql.append("'" + z.newZid(table.getTable_id()) + "',");
                        }else if("7".equals(column.getColumn_default_type())) {//连续数字编号
                            sql.append("'"+newContinuityNumber(table.getTable_id())+"',");
                        }
                    }

                }

            }
            sql.append("'" + bean.get("session_userid") + "',");//创建者

            if (z.isNotNull(bean.get("create_time"))) {
                sql.append("'" + bean.get("create_time") + "',");//创建时间
            } else {
                sql.append("now(),");//创建时间
            }
            sql.append("'" + bean.get("session_userid") + "',");//修改者

            if (z.isNotNull(bean.get("update_time"))) {
                sql.append("'" + bean.get("update_time") + "',");//修改时间
            } else {
                sql.append("now(),");//修改时间
            }

            sql.append("'" + bean.get("session_orgid") + "',");//所属组织
            sql.append("0,");//版本号
            sql.append("'" + bean.get("zid") + "' )");//zid
            return sql.toString();
        } else {
            return null;
        }

    }


    private void insertBefore(HashMap<String, String> bean, z_form_table table, HashMap<String, z_form_table_column> columnMap, List<z_form_table_column> columnList) throws Exception {
        for (z_form_table_column column : columnList) {
            String name = column.getColumn_id();//获取参数名
            String value = bean.get(column.getColumn_id());
            if (!"zid".equals(name)
                    && !"create_user".equals(name)
                    && !"update_user".equals(name)
                    && !"create_time".equals(name)
                    && !"update_time".equals(name)
                    && !"seq".equals(name)
                    && !"orgid".equals(name)
                    && !"zversion".equals(name)
                    && column != null) {
                if (z.isNotNull(value)) {
                    //字段必须是表定义中包含的字段
                    if (z.isNotNull(columnMap.get(name))) {
                        //验证是否唯一
                        if ("1".equals(column.getIs_only())) {
                            int n = selectInt("select count(*) n from " + table.getTable_id() + " where " + name + "='" + value + "'");
                            if (n > 0) {
                                z.Exception("insert异常|[" + column.getColumn_name() + "]值重复,违反唯一性要求，无法保存");
                            }
                        }

                        //验证有正则表达式的字段
                        if (z.isNotNull(column.getRegex())) {
                            z_regex r = z.regexs.get(column.getRegex());
                            if (z.isNotNull(r) && z.isNotNull(r.getRegex())) {
                                boolean v = StringUtil.vRegex(value, r.getRegex());
                                if (!v) {
                                    z.Exception("insert异常|[" + column.getColumn_name() + "]数据值校验失败");
                                }
                            }
                        }


                    }
                }
            }
        }

    }

    private void insertAfter(HashMap<String, String> bean, z_form_table table, HashMap<String, z_form_table_column> columnMap, List<z_form_table_column> columnList) throws Exception {
    }

    protected int selectInt(String sql) {
        return sqlSession.selectOne("selectoneint", sql);
    }

}
